import { message } from "antd";
import axios, { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from "axios";


const _axios: AxiosInstance = axios.create({
    baseURL: "",
    headers: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
    timeout: 5000,
})

// 解决报错 类型“AxiosResponse<any, any>”上不存在属性“meta”
declare module "axios" {
    interface AxiosResponse<T = any> {
        meta: any;
    }
    export function create(config?: AxiosRequestConfig): AxiosInstance;
}

// 请求拦截器
_axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    return config;
});

// 响应拦截器
_axios.interceptors.response.use(
    (response: AxiosResponse) => {
        // 这里可以处理响应数据，例如统一错误处理、数据转换等
        if (response.data.code != 200) {
            message.error(response.data.message)
            return Promise.reject(response.data.message)
        } else {
            return response.data;
        }
    },
    (error: AxiosError) => {
        // 这里可以处理请求错误，例如统一错误提示、跳转登录页等
        return Promise.reject(error);
    }
)

export default _axios